/**
 * Created by John on 2017/9/18.
 */
var https = require('../utils/httpsSendMethod');
var wxConfig = require('config').get("wxConfig");
var restler = require('restler');
var fs = require('fs');

var url = {
    access_token_url : 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + wxConfig.corpid + '&corpsecret=' + wxConfig.corpsecret,
    user_info_url : 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE',
    user_detail_url : 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token=ACCESS_TOKEN',
    upload_file_url : 'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE',
    send_message_url : 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN'
};

var cache = {
    accessToken:{},
    getAccessToken:function () {
      var tokenInfo = this.accessToken;
      if (tokenInfo.access_token){
          var duration = (+new Date()-tokenInfo.timestamp)/1000;
          if (duration<tokenInfo.expires_in){
              return tokenInfo.access_token;
          }
      }
      return null;
    },
    userTicket:{},
    getUserTicket:function (userId) {
        var userTicket = this.userTicket[userId];
        if (userTicket){
            var duration = (+new Date()-userTicket.timestamp)/1000;
            if (duration<userTicket.expires_in){
                return userTicket.user_ticket;
            }
        }
        return null;
    }
};

module.exports = {
    getAccessToken:function (callback) {
        var access_token = cache.getAccessToken();
        if(access_token){//使用缓存的access_token
           callback(null, access_token);
           return;
        }
        https.getJSON(url.access_token_url, function (err,data) {//从微信服务器获取access_token
            if(data){
                if (data.errcode==0){
                    cache.accessToken = {
                        access_token : data.access_token,
                        expires_in : data.expires_in,
                        timestamp : +new Date()
                    };
                    callback(null, data.access_token);
                }else{
                    console.log(data.errmsg);
                    callback(data.errmsg);
                }
            }else{
                callback(err);
            }
        });
    },
    getUserInfo:function (code,callback) {
        this.getAccessToken(function (err,access_token) {
            if (access_token){
                https.getJSON(url.user_info_url.replace('ACCESS_TOKEN',access_token).replace('CODE',code),function (err, data) {
                    if(data){
                        if (data.errcode==0){
                            cache.userTicket[data.UserId] = {
                                user_ticket: data.user_ticket,
                                expires_in: data.expires_in,
                                timestamp : +new Date()
                            };
                            callback(null, data);
                        }else{
                            console.log(data.errmsg);
                            callback(data.errmsg);
                        }
                    }else{
                        callback(err);
                    }
                });
            }else{
                callback(err);
            }
        });
    },
    getUserDetail:function (UserId,callback) {
        var user_ticket = cache.getUserTicket(UserId);
        if (user_ticket){
            this.getAccessToken(function (err,access_token) {
                if (access_token){
                    restler.post(url.user_detail_url.replace('ACCESS_TOKEN',access_token), {
                        data: JSON.stringify({user_ticket:user_ticket}),
                    }).on('complete', function(data, response) {
                        // data = JSON.parse(data);
                        if (data.errcode==0){
                            data = {avatar:data.avatar};
                            callback(null, data);
                        }else{
                            callback(data.errmsg, null);
                        }
                    });
                }else{
                    callback(err);
                }
            });
        }else{
            callback('user_ticket not found, pls call getUserInfo as a init first');
        }
    },
    uploadExcel:function (filename,filepath,callback) {
        this.getAccessToken(function (err,access_token) {
            if (access_token){
                restler.post(url.upload_file_url.replace('ACCESS_TOKEN',access_token).replace('TYPE','file'), {
                    multipart: true,
                    data: {
                        'media[file]': restler.file(filepath, filename, fs.statSync(filepath).size, null, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
                    }
                }).on('complete', function(data) {
                    if (data.errcode==0){
                        callback(null, data.media_id);
                    }else{
                        callback(data.errmsg, null);
                    }
                });
            }else{
                callback(err);
            }
        });
    },
    createMsg:function (userId,msgtype,msgbody) {
       var data = {touser: userId, msgtype:msgtype, agentid:wxConfig.agentid};
       data[msgtype] = msgbody;
       return data;
    },
    sendMsg:function (msg,callback) {
        this.getAccessToken(function (err,access_token) {
            if (access_token){
                restler.post(url.send_message_url.replace('ACCESS_TOKEN',access_token), {
                    data: JSON.stringify(msg),
                }).on('complete', function(data, response) {
                    data = JSON.parse(data);
                    if (data.errcode==0){
                        callback(null, data);
                    }else{
                        callback(data.errmsg, null);
                    }
                });
            }else{
                callback(err);
            }
        });
    }
}